package com.simtop.controller;


import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simtop.common.MyRespose;
import com.simtop.common.ServerResponse;
import com.simtop.pojo.logpo.Operate;
import com.simtop.pojo.userpo.User;
import com.simtop.pojo.userpo.UserExamVo;
import com.simtop.service.KsServer;
import com.simtop.service.SjServer;
import com.simtop.service.impl.SjServerImpl;
import com.simtop.util.ZipUtils.ZipUtils;
import com.simtop.util.fileutil.FileUploadAndDownload;
import com.simtop.util.fileutil.FileUtil;
import com.simtop.util.jwtutil.JwtUtil;
import com.simtop.util.worldUtil.PdfUtil;
import com.simtop.util.worldUtil.WordDoc;
import com.simtop.vo.exam.ExamVo;
import com.simtop.vo.exam.ExamVos;
import com.simtop.vo.sj.*;
import com.simtop.vo.word.WoVo;
import com.simtop.vo.word.WordExamSjVo;
import com.simtop.vo.word.WordExamVo;
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.MultipartFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import static com.simtop.common.Resources.FileUrl;
import static com.simtop.common.Resources.Http;

@RestController
@CrossOrigin
@RequestMapping("/sj")
public class SjController {

    @Autowired
    private SjServer sjServer;

    @Autowired
    private KsServer ksServer;


    /**
     * @Author: liuzhaobo
     * @Description: 获取题目
     * @DateTime: 2022/10/12 0012 11:59
     * @Params:
     * @Return
     */
    @RequestMapping("/findAllSj")
    @ResponseBody
    public ServerResponse<Object> getOperate(@RequestBody String data, MultipartFile file, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            JSONObject entries = JSONUtil.parseObj(data);
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            if (StringUtils.isEmpty(pageNum) || pageNum == 0) {
                pageNum = 1;
            }
            if (StringUtils.isEmpty(pageSize) || pageSize == 0) {
                pageSize = 10000;
            }
            String op = entries.getStr("op");
            String px = entries.getStr("px");
            Integer dodId = entries.getInt("dodId");
            Integer tableId = entries.getInt("tableId");
            Integer sjtypeId = entries.getInt("sjtypeId");
            String search = entries.getStr("search");
            Integer lasttypeId = entries.getInt("lasttypeId");
            PageHelper.startPage(pageNum, pageSize);
            List<sjVo> allSj = sjServer.getAllSj(op, px, dodId, tableId, sjtypeId, search, lasttypeId);
            for (sjVo as : allSj
            ) {
                Integer id = as.getId();
                List<ResourceFj> courseVos = sjServer.getListSjScource(id);
                for (ResourceFj asa : courseVos
                ) {
                    asa.setFjurl(Http + asa.getFjurl());

                }

                if (courseVos.size() > 0) {
                    as.setResourceFjs(courseVos);
                }


            }
            PageInfo<sjVo> pageInfo = new PageInfo<sjVo>(allSj);


            return ServerResponse.createBySuccess("获取成功", pageInfo);


        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("获取失败");
        }
    }


    /**
     * @Author: liuzhaobo
     * @Description: 新增题目
     * @DateTime: 2022/10/12 0012 11:59
     * @Params:
     * @Return
     */
    @RequestMapping("/insertSj")
    @ResponseBody
    public ServerResponse<Object> insertSj(InsertJsVo insertJsVo, MultipartFile[] file, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }


            boolean i = sjServer.insertSj(insertJsVo);
            Integer sjid = insertJsVo.getId();

            if (file != null) {
                for (MultipartFile as : file
                ) {

                    FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
                    String upload = fileUploadAndDownload.upload(as);
                    String originalFilename = as.getOriginalFilename();
                    String[] split = originalFilename.split("\\.");
                    String namesj = split[0];
                    String typesj = split[1];

                    sjServer.insertSjcources(upload, sjid, namesj, typesj);

                }
            }


            if (i) {
                return ServerResponse.createBySuccess("新增成功");
            } else {
                return ServerResponse.createByErrorMsg("新增失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ServerResponse.createByErrorMsg("新增失败");
        }


    }

    /**
     * @Author: liuzhaobo
     * @Description: 获取科目类型标签
     * @DateTime: 2022/10/20 0020 16:05
     * @Params:
     * @Return
     */
    @RequestMapping("/getSjType")
    @ResponseBody
    public ServerResponse<Object> getSjType() {
        List<SjTypeVo> sjTypeVos = sjServer.getSjType();
        for (SjTypeVo as : sjTypeVos
        ) {
            Integer id = as.getId();
            List<LastTypeVo> lastname = sjServer.getlasttype(id);
            ArrayList<LastTypeVo> objects = new ArrayList<>();
            if (lastname.size() > 0) {
                for (LastTypeVo asa : lastname
                ) {
                    LastTypeVo lastTypeVo = new LastTypeVo();
                    lastTypeVo.setId(asa.getId());
                    lastTypeVo.setLastname(asa.getLastname());
                    objects.add(lastTypeVo);

                }
                as.setData(objects);

            }

        }

        HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("sj", sjTypeVos);

        return ServerResponse.createBySuccess(objectObjectHashMap);

    }

    /**
     * @Author: liuzhaobo
     * @Description: 上传图片 返回http
     * @DateTime: 2022/10/21 0021 9:39
     * @Params:
     * @Return
     */
    @RequestMapping("/insertPng")
    @ResponseBody
    public MyRespose insertPng(Sjsj sjsj, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                MyRespose myRespose = new MyRespose();
                myRespose.setMsg("token不存在");
                return myRespose;
            }
            Integer sjId = sjsj.getSjId();
            FileUploadAndDownload fileUploadAndDownload = new FileUploadAndDownload();
            String upload = fileUploadAndDownload.upload(sjsj.getFile());
            String originalFilename = sjsj.getFile().getOriginalFilename();
            String[] split = originalFilename.split("\\.");
            String namesj = split[0];
            String typesj = split[1];
            sjServer.insertPng(upload, namesj, typesj, sjId);
            //return ServerResponse.createBySuccess("http://192.168.0.121" + upload);
            String url = Http + upload;
            JSONObject jsonObject = new JSONObject();
            JSONObject jsonObject1 = new JSONObject();
            jsonObject1.put("url", url);
            jsonObject.put("errno", 0);
            jsonObject.put("data", jsonObject1);
            MyRespose myRespose = new MyRespose();
            myRespose.setUrl(url);
            myRespose.setMsg("上传成功");
            myRespose.setPcname(namesj);
            return myRespose;
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("errno", 1);
            jsonObject.put("message", "失败信息");
            MyRespose myRespose = new MyRespose();
            myRespose.setMsg("上传失败");
            return myRespose;
        }

    }

    /**
     * @Author: liuzhaobo
     * @Description: 修改试题
     * @DateTime: 2022/10/21 0021 11:03
     * @Params:
     * @Return
     */
    @RequestMapping("/updateSj")
    @ResponseBody
    public ServerResponse<Object> updateSj(InsertJsVo insertJsVo, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }

            int i = sjServer.updateSj(insertJsVo);
            if (i > 0) {
                return ServerResponse.createBySuccess("修改成功");
            } else {
                return ServerResponse.createBySuccess("修改失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("修改失败");
        }


    }


    /**
     * @Author: liuzhaobo
     * @Description: 删除试题
     * @DateTime: 2022/10/21 0021 13:05
     * @Params:
     * @Return
     */
    @RequestMapping("/deleteSj")
    @ResponseBody
    public ServerResponse<Object> deleteSj(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }

            JSONObject entries = JSONUtil.parseObj(data);
            Integer id = entries.getInt("id");
            int i = sjServer.deleteSj(id);
            if (i > 0) {
                return ServerResponse.createBySuccess("删除成功");
            } else {
                return ServerResponse.createByErrorMsg("删除失败");
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }

    /**
     * @Author: liuzhaobo
     * @Description: 新增试卷
     * @DateTime: 2022/10/21 0021 13:05
     * @Params:
     * @Return
     */
    @RequestMapping("/insertExam")
    @ResponseBody
    public ServerResponse<Object> insertExam(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            String username = u.getUsername();
            JSONObject entries = JSONUtil.parseObj(data);
            JSONArray sjId = entries.getJSONArray("sjId");
            String examName = entries.getStr("examName");
            Integer examTime = entries.getInt("examTime");
            Integer assessMent = entries.getInt("assessMent");
            ExamVo examVo = new ExamVo();
            examVo.setExamTime(examTime);
            examVo.setUsername(username);
            examVo.setExamName(examName);
            examVo.setAssessMent(assessMent);
            //先新增试卷
            boolean i = sjServer.insertExam(examVo);
            Integer examId = examVo.getId();
            if (sjId.size() > 0) {
                for (Object sjIds : sjId
                ) {
                    sjServer.insertExamSj(examId, (Integer) sjIds);
                }
            }

            return ServerResponse.createBySuccessMsg("新增试卷成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("新增试卷失败");

        }


    }

    /**
     * @Author: liuzhaobo
     * @Description: 查看试卷
     * @DateTime: 2022/10/21 0021 14:48
     * @Params:
     * @Return
     */
    @RequestMapping("/findExam")
    @ResponseBody
    public ServerResponse<Object> findExam(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            Integer ids = u.getId();
            JSONObject entries = JSONUtil.parseObj(data);
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            String op = entries.getStr("op");
            String px = entries.getStr("px");
            String examName = entries.getStr("examName");
            PageHelper.startPage(pageNum, pageSize);
            List<ExamVos> allSj = sjServer.findExam(op, px, examName);
            for (ExamVos as : allSj
            ) {
                Integer id = as.getId();
                int peoper = sjServer.findCount(id);
                as.setCountpeoper(peoper);
                //查询已经做的次数
                int i = ksServer.findkhCount(ids, id);
                as.setStuExamCount(i);
            }
            PageInfo<ExamVos> pageInfo = new PageInfo<ExamVos>(allSj);
            return ServerResponse.createBySuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("查看失败");
        }

    }


    /**
     * @Author: liuzhaobo
     * @Description: 查看试卷
     * @DateTime: 2022/10/21 0021 14:48
     * @Params:
     * @Return
     */
    @RequestMapping("/findExam2")
    @ResponseBody
    public ServerResponse<Object> findExam2(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            Integer ids = u.getId();
            JSONObject entries = JSONUtil.parseObj(data);
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            String op = entries.getStr("op");
            String px = entries.getStr("px");
            String examName = entries.getStr("examName");
            PageHelper.startPage(pageNum, pageSize);
            List<ExamVos> allSj = sjServer.findExam(op, px, examName);
            for (ExamVos as : allSj
            ) {
                Integer id = as.getId();
                int peoper = sjServer.findCount(id);
                as.setCountpeoper(peoper);
                //查询已经做的次数
                int i = ksServer.findkhCount2(ids, id);
                as.setStuExamCount(i);
            }
            PageInfo<ExamVos> pageInfo = new PageInfo<ExamVos>(allSj);
            return ServerResponse.createBySuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("查看失败");
        }

    }


    /**
     * @Author: liuzhaobo
     * @Description: 查看试卷2
     * @DateTime: 2022/10/21 0021 14:48
     * @Params:
     * @Return
     */
    @RequestMapping("/findExamUser")
    @ResponseBody
    public ServerResponse<Object> findExamUser(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            Integer ids = u.getId();
            JSONObject entries = JSONUtil.parseObj(data);
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            String op = entries.getStr("op");
            String px = entries.getStr("px");
            String examName = entries.getStr("examName");
            PageHelper.startPage(pageNum, pageSize);
            List<ExamVos> allSj = sjServer.findExamUser(op, px, examName);
            ArrayList<ExamVos> objects = new ArrayList<ExamVos>();
            for (ExamVos as : allSj
            ) {
                Integer id = as.getId();

                int peoper = sjServer.findCount(id);

                as.setCountpeoper(peoper);

                //查询已经做的次数
                int i = ksServer.findkhCount(ids, id);
                if (i == 0) {
                    //无记录就剔除
                    objects.add(as);


                }
                as.setStuExamCount(i);
            }
            allSj.removeAll(objects);
            ArrayList<ExamVos> objects1 = new ArrayList<ExamVos>();
            for (ExamVos as : allSj
            ) {
                objects1.add(as);
            }


            PageInfo<ExamVos> pageInfo = new PageInfo<ExamVos>(objects1);
            return ServerResponse.createBySuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("查看失败");
        }

    }


    /**
     * @Author: liuzhaobo
     * @Description: 查看试卷2
     * @DateTime: 2022/10/21 0021 14:48
     * @Params:
     * @Return
     */
    @RequestMapping("/DeleteExamUser")
    @ResponseBody
    public ServerResponse<Object> DeleteExamUser(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            Integer ids = u.getId();
            JSONObject entries = JSONUtil.parseObj(data);
            Integer examId = entries.getInt("examId");
            sjServer.DeleteExamUser(examId);


            return ServerResponse.createBySuccess("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return ServerResponse.createByErrorMsg("删除失败");
        }

    }

    /**
     * @Author: liuzhaobo
     * @Description: 点击试卷查看试题
     * @DateTime: 2022/10/21 0021 16:18
     * @Params:
     * @Return
     */
    @RequestMapping("/findExamSj")
    @ResponseBody
    public ServerResponse<Object> findExamSj(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            JSONObject entries = JSONUtil.parseObj(data);
            Integer examId = entries.getInt("examId");
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            String op = entries.getStr("op");
            String px = entries.getStr("px");
            PageHelper.startPage(pageNum, pageSize);
            List<sjVo> allSj = sjServer.findExamSj(examId, op, px);
            for (sjVo as : allSj
            ) {
                Integer id = as.getId();
                List<ResourceFj> courseVos = sjServer.getListSjScource(id);
                for (ResourceFj asa : courseVos
                ) {
                    asa.setFjurl(Http + asa.getFjurl());
                }

                if (courseVos.size() > 0) {
                    as.setResourceFjs(courseVos);
                }


            }
            PageInfo<sjVo> pageInfo = new PageInfo<sjVo>(allSj);
            return ServerResponse.createBySuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ServerResponse.createByErrorMsg("查看失败");
        }
    }


    /**
     * @Author: liuzhaobo
     * @Description: 根据试卷id查询考试用户
     * @DateTime: 2022/10/21 0021 16:18
     * @Params:
     * @Return
     */
    @RequestMapping("/findExamSjById")
    @ResponseBody
    public ServerResponse<Object> findExamSjById(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            JSONObject entries = JSONUtil.parseObj(data);
            Integer examId = entries.getInt("examId");
            Integer pageNum = entries.getInt("pageNum");
            Integer pageSize = entries.getInt("pageSize");
            PageHelper.startPage(pageNum, pageSize);
            List<UserExamVo> examNameUser = sjServer.getExamNameUser(examId);
            PageInfo<UserExamVo> pageInfo = new PageInfo<UserExamVo>(examNameUser);
            return ServerResponse.createBySuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ServerResponse.createByErrorMsg("查看失败");
        }
    }

    /**
     * @Author: liuzhaobo
     * @Description: 修改试卷
     * @DateTime: 2022/10/21 0021 17:36
     * @Params:
     * @Return
     */
    @RequestMapping("/updateExam")
    @ResponseBody
    public ServerResponse<Object> updateExam(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            JSONObject entries = JSONUtil.parseObj(data);
            Integer examId = entries.getInt("examId");
            Integer examTime = entries.getInt("examTime");
            Integer assessMent = entries.getInt("assessMent");
            String examName = entries.getStr("examName");
            sjServer.updateExames(examId, examTime, assessMent, examName);
            //删除试卷id
            sjServer.deleteExamByid(examId);
            //循环添加试卷id 对应的 试题id
            JSONArray sjId = entries.getJSONArray("sjId");
            if (sjId.size() > 0) {
                for (Object sjIds : sjId
                ) {
                    sjServer.insertExamSj(examId, (Integer) sjIds);
                }
            }

            return ServerResponse.createBySuccessMsg("更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ServerResponse.createByErrorMsg("更新失败");
        }

    }

    /**
     * @Author: liuzhaobo
     * @Description: 删除试卷
     * @DateTime: 2022/10/21 0021 17:52
     * @Params:
     * @Return
     */
    @RequestMapping("/deleteExam")
    @ResponseBody
    public ServerResponse<Object> deleteExam(@RequestBody String data, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            String jwt = token.substring(token.lastIndexOf(" ") + 1);
            User u = JwtUtil.unsign(jwt, User.class);
            if (u == null) {
                return ServerResponse.createByErrorMsg("token无效");
            }
            JSONObject entries = JSONUtil.parseObj(data);
            Integer examId = entries.getInt("examId");
            int i = sjServer.deleteExam(examId);
            if (i > 0) {
                return ServerResponse.createBySuccess("删除成功");
            } else {
                return ServerResponse.createBySuccess("删除失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return ServerResponse.createByErrorMsg("删除失败");
        }
    }

    /**
     * @Author: liuzhaobo
     * @Description: 删除试卷
     * @DateTime: 2022/10/21 0021 17:52
     * @Params:
     * @Return
     */
    @GetMapping("/importExams")
    public void importExams(Integer examId, HttpServletRequest request, HttpServletResponse response) {

        try {
            //获取试卷信息
            ExamVos examVos = sjServer.findOneExam(examId);
            if (examVos != null) {
                WordDoc wordDoc = new WordDoc();
                Map<String, Object> dataMap = new HashMap<String, Object>();
                dataMap.put("examName", examVos.getExamName());
                dataMap.put("examUser", examVos.getExamUser());
                dataMap.put("examTime", examVos.getExamTime());
                //循环 找到 所有的题型
                List<Map<String, Object>> list = new ArrayList<>();

                List<WordExamVo> wordExamVos = sjServer.findwordExamVos(examId);
                int i = 0;
                String asi = "";
                for (WordExamVo as : wordExamVos
                ) {
                    i++;
                    if (i == 1) {
                        asi = "一、";
                    }
                    if (i == 2) {
                        asi = "二、";
                    }
                    if (i == 3) {
                        asi = "三、";
                    }
                    if (i == 4) {
                        asi = "四、";
                    }

                    List<Map<String, Object>> list2 = new ArrayList<>();
                    Integer sjcount = as.getSjcount();
                    String sjtype = as.getSjtype();
                    if (sjtype.equals("选择题")) {
                        //循环 题目
                        Integer tableId = 1;
                        List<WordExamSjVo> wordExamSjVoList = sjServer.findWordExamSj(examId, tableId);
                        for (WordExamSjVo asa : wordExamSjVoList
                        ) {
                            String optionText = asa.getOptionText();
                            String optionAnswer = asa.getOptionAnswer();
                            JSONArray array = JSONUtil.parseArray(optionAnswer);

                            List<WoVo> woVoList = JSONUtil.toList(array, WoVo.class);
                            String optionname = "";
                            for (WoVo asas : woVoList
                            ) {
                                String content = asas.getContent();
                                String seq = asas.getSeq();
                                content = content.replaceAll("<[^>]+>", "");
                                optionname = seq + ":" + content + "       " + optionname;
                                //  System.out.println(optionname);
                            }


                            Map<String, Object> mapas = new HashMap<>();
                            mapas.put("optionsj", optionText);
                            mapas.put("optionname", optionname);
                            list2.add(mapas);
                        }


                    }
                    if (sjtype.equals("判断题")) {
                        //循环 题目
                        Integer tableId = 2;
                        List<WordExamSjVo> wordExamSjVoList = sjServer.findWordExamSj(examId, tableId);
                        for (WordExamSjVo asa : wordExamSjVoList
                        ) {
                            String optionText = asa.getOptionText();
                            Map<String, Object> mapas2 = new HashMap<>();
                            mapas2.put("optionsj", optionText);
                            mapas2.put("optionname", "A: 对         B: 错");
                            list2.add(mapas2);
                        }
                    }
                    if (sjtype.equals("填空题")) {
                        //循环 题目
                        Integer tableId = 3;
                        int j = 1003;
                        List<WordExamSjVo> wordExamSjVoList = sjServer.findWordExamSj(examId, tableId);
                        for (WordExamSjVo asa : wordExamSjVoList
                        ) {
                            i = ++j;
                            String optionText = asa.getOptionText();
                            String bate = asa.getBate().replace("\\", "/");
                            String imageStr = wordDoc.ImageToBase64ByOnline(bate);
                            Map<String, Object> mapas3 = new HashMap<>();
                            mapas3.put("optionsj", optionText);
                            mapas3.put("paps", imageStr);
                            mapas3.put("papsname", "001" + j);
                            list2.add(mapas3);
                        }
                    }

                    if (sjtype.equals("计算题")) {
                        //循环 计算题
                        Integer tableId = 4;
                        List<WordExamSjVo> wordExamSjVoList = sjServer.findWordExamSj(examId, tableId);
                        int j = 1004;
                        for (WordExamSjVo asa : wordExamSjVoList
                        ) {
                            i = ++j;
                            String optionText = asa.getOptionText();
                            String bate = asa.getBate().replace("\\", "/");
                            String imageStr = wordDoc.ImageToBase64ByOnline(bate);
                            Map<String, Object> mapas2 = new HashMap<>();
                            mapas2.put("optionsj", optionText);
                            mapas2.put("paps", imageStr);
                            mapas2.put("papsname", "001" + j);
                            list2.add(mapas2);
                        }

                    }
                    Map<String, Object> SjTypeMap = new HashMap<>();
                    SjTypeMap.put("type", asi + sjtype);
                    SjTypeMap.put("count", sjcount);
                    SjTypeMap.put("ExamChead", list2);
                    list.add(SjTypeMap);
                }


                dataMap.put("ExamList", list);


                String reName = "D:/" + examVos.getExamName() + "-" + examVos.getExamUser() + "-" + UUID.randomUUID() + ".doc";
                wordDoc.createWord(dataMap, "Exam006.ftl", reName);

                File file = new File(reName);
                String name = file.getName();
                String ext = name.substring(name.lastIndexOf(".") + 1).toUpperCase();
                // 以流的形式下载文件。
                InputStream fis = new BufferedInputStream(new FileInputStream(reName));
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(reName, "UTF-8"));
                response.addHeader("Content-Length", "" + file.length());
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                response.setContentType("application/octet-stream");
                toClient.write(buffer);
                toClient.flush();
                toClient.close();

            }


        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());

        }

    }

    @PostMapping("/importExamsPDF")
    public ServerResponse<Object> importExamsPDF(Integer userid, Integer stuexamid, MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        //下载 pdf文件到本地
        OutputStream os = null;
        InputStream inputStream = null;
        String fileName = null;
        String StuFileForPdf = null;
        try {
            inputStream = file.getInputStream();
            fileName = file.getOriginalFilename();
/*            String[] split = fileName.split("\\.");
            String Uuid = UUID.randomUUID().toString();
            String s1 = split[0];
            StuFileForPdf = s1 + Uuid + ".pdf";*/
            int i = sjServer.updateForPdf(userid, stuexamid, fileName);
            //String path = "E:\\test\\";
            String path = FileUrl;
            //线上改成 Url
            // 2、保存到临时文件
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流保存到本地文件
            File tempFile = new File(path);
            if (!tempFile.exists()) {
                tempFile.mkdirs();
            }
            os = new FileOutputStream(tempFile.getPath() + File.separator + fileName);
            // 开始读取
            while ((len = inputStream.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
         /*   //下载pdf

            FileInputStream is = new FileInputStream(new File("D:\\test\\形拓Nginx统一配置.pdf"));
            // 清空response
            response.reset();
            //2、设置文件下载方式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode("形拓Nginx统一配置","utf-8")+".pdf");
            OutputStream outputStream = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();

*/
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 完毕，关闭所有链接
            try {
                os.close();
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ServerResponse.createBySuccessMsg("成功");
    }

    @GetMapping("/packageFileToZip")
    public ServerResponse<Object> packageFileToZip(Integer examid, String examname, HttpServletRequest request, HttpServletResponse response) {
        try {
            //查询所有url
            List<String> fileas = sjServer.findListAllStu(examid);


            // 为了方便我直接将文件地址写好了，各位可以根据自己的情况修改
            //       String[] filePath = new String[]{"E:\\test\\嘻嘻哈哈.pdf", "E:\\test\\啊实打实的.pdf"};
            // 将需要打包的文件都放在一个集合中
            List<File> fileList = new ArrayList<>();
            for (String s : fileas) {
                // File file = new File("E:\\test\\" + s);
                File file = new File(FileUrl + s);

                fileList.add(file);
            }
            // 先在D盘创建一个压缩包
            String Uuid = UUID.randomUUID().toString();
            File zipFile = new File(FileUrl+ Uuid + ".zip");
            if (!zipFile.exists()) {
                zipFile.createNewFile();
            }
            // 将package.zip的File对象传到toZip对象中
            ZipUtils.toZip(fileList, zipFile);


            FileInputStream is = new FileInputStream(new File(FileUrl + Uuid + ".zip"));
            // 清空response
            response.reset();
            //2、设置文件下载方式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(examname, "utf-8") + ".zip");
            OutputStream outputStream = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
        return ServerResponse.createBySuccessMsg("成功");
    }


    @GetMapping("/importExamsByStu")
    public ServerResponse<Object> importExamsByStu(Integer id, String examname, HttpServletRequest request, HttpServletResponse response) {
        try {
            String fileas = sjServer.findListAllStuForEx(id);
            String[] split = fileas.split("\\.");
            String s = split[0];
            s = URLEncoder.encode(s, "UTF-8");//转码
            s = s.replace("+", "%20");
            //  FileInputStream is = new FileInputStream(new File("E:\\test\\" + fileas));
            FileInputStream is = new FileInputStream(new File(FileUrl + fileas));
            // 清空response
            response.reset();
            //2、设置文件下载方式
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;filename=" + s + ".pdf");
            OutputStream outputStream = response.getOutputStream();
            int count = 0;
            byte[] buffer = new byte[1024 * 1024];
            while ((count = is.read(buffer)) != -1) {
                outputStream.write(buffer, 0, count);
            }
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();

            return ServerResponse.createByErrorMsg("失败");
        }
        return ServerResponse.createBySuccessMsg("成功");
    }

    @PostMapping("/pdfImport")
    public void pdfImport(MultipartFile files, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 将MultiparFile转为File
            File file = PdfUtil.multipartToFile(files);

            // 创建Pdf工具类对象
            PdfDocument pdf = new PdfDocument();

            // 拼接Word文件名
            String projectPath = System.getProperty("user.dir");
            String name = file.getName();
            pdf.loadFromFile(projectPath + "/" + name);

            //保存为Word格式
            String fileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + ".docx";
            pdf.saveToFile(fileName, FileFormat.DOCX);

            // 将问文件转为字节流返回供前端下载
            File wordFile = new File(fileName);
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");

            // 下载文件能正常显示中文
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));

            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(wordFile);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                System.out.println("word文件下载成功");
            } catch (Exception e) {
                System.out.println("word文件下载失败");
            } finally {
                if (bis != null) {
                    try {
                        // 结束后关闭文件流
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        // 结束后关闭文件流
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                // 最后删除转换过程中生成的文件
                wordFile.delete();
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }


    }
}